package cn.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;

public class DAServerSocket extends Thread {

	private DAPolicyServerSocket policySS = null;
	private static ServerSocket server = null;
	private boolean start = true;
	public static Map<String, Socket> userHash = null;
	public static Map<String, Socket> groupHash = null;

	public DAServerSocket() {
		userHash = new WeakHashMap<String, Socket>();
		userHash = Collections.synchronizedMap(userHash);
		policySS = new DAPolicyServerSocket();
		try {
			server = new ServerSocket(8888);
		} catch (Exception e) {
			System.out.println("In DAServerSocket DAServerSocket...");
		}
	}

	public void startServer() {
		this.start();
	}

	public void run() {
		this.policySS.start();// start the policy file server port 843
		try {
			while (start) {
				new SendMessage(server.accept()).start();// start listenning the
				// 8888 ports
			}
		} catch (IOException e) {
			System.out.println("In DAServerSocket run...");
		} finally {
			try {
				if (userHash != null) {
					userHash = null;
				}
				if (null != server) {
					server.close();
				}
			} catch (IOException e) { // TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public boolean stopServer() {
		this.policySS.stopServer();
		this.start = false;
		try {
			if (DAServerSocket.userHash != null)
				DAServerSocket.userHash = null;
			if (DAServerSocket.server != null)
				DAServerSocket.server.close();
		} catch (IOException e) {
			System.err.println("In DAServerSocket stopServer...");
			return false;
		}
		return true;
	}

	public boolean isStart() {
		return start;
	}
}
